package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import data.Data;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

@SuppressWarnings("serial")
public class ForgotPasswordServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		String[] listError = new String[2];

		request.setAttribute("listError", listError);

		try {
			request.getRequestDispatcher("/forgot_password.jsp").forward(
					request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		String[] listError = new String[2];

		String email = (String) request.getParameter("email");
		DBCollection collection = Data.data("users");
		DBObject dbObject=null;
		if(email !=null)
		{
			dbObject = collection.findOne(new BasicDBObject("email",email));
			if(dbObject==null)
			{
				listError[0]="Email incorrect !";
			}
		}
		
		//check capchar
		String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        reCaptcha.setPrivateKey("6LcF-80SAAAAAM2kArjyUwtVJYbH_DKredY3Q26U");

        String challenge = request.getParameter("recaptcha_challenge_field");
        String uresponse = request.getParameter("recaptcha_response_field");
        if(challenge == null)
        {
        	challenge = "b";
        }
        if(uresponse == null)
        {
        	uresponse = "a";
        }
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

        if (!reCaptchaResponse.isValid()) {
        	listError[1] = "Invalid Capchar";
        }
		
        if(listError[0]==null&&listError[1]==null)
        {
        	try {
        		int rand = new Random().nextInt(1000);
        		String code = Utils.md5(dbObject.get("email").toString()+String.valueOf(rand));
        		
        		dbObject.put("forgot", code);
        		collection.save(dbObject);
        		
				String mesage = "<p>Click the link bellow to get the new password</p>"+"<a href='http://hatforrent.com/forgot/"+code+"'>http://hatforrent.com/forgot/"+code+"</a>"+"<p>Please note that this link is only active for one time</p>";
	            URL url = new URL("http://send-emails.appspot.com/sendemail");
	            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	            connection.setDoOutput(true);
	            connection.setRequestMethod("POST");
	            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
	            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
	            writer.write("email="+dbObject.get("email"));
	            writer.write("&name_email="+dbObject.get("email"));
	            writer.write("&from_email=admin@hatforrent.com");
	            writer.write("&subject=Mail forgot password from hatforrent.com ");
	            writer.write("&content="+mesage);
	            writer.close();
	    
	            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
	            	 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	            }
	            request.setAttribute("success", "true");
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
        }
        
		request.setAttribute("listError", listError);

		try {
			request.getRequestDispatcher("/forgot_password.jsp").forward(
					request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
